package net.wanho.service.impl;

import net.wanho.po.User;
import net.wanho.mapper.UserMapper;
import net.wanho.service.FileService;
import net.wanho.service.UserService;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 汤小洋
 * @since 2025-09-25
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final FileService fileService;

    /**
     * 用户表分页查询
     * @param pageNum
     * @param pageSize
     * @param user
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo findPage(int pageNum, int pageSize, User user) {
        if(ObjectUtil.isNull(user)){
            user = new User();
        }

        // 分页
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.select(user);
        return new PageInfo(userList);
    }

    /**
     * 根据主键查询用户表
     * @param id
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User findById(Serializable id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户表新增
     * @param user
     */
    @Override
    public void add(User user) {
        userMapper.insert(user);
    }

    /**
     * 修改用户表
     * @param user
     */
    @Override
    public void modify(User user) {
        userMapper.update(user);
    }

    /**
     * 根据主键删除用户表
     * @param id
     */
    @Override
    public void removeById(Serializable id) {
        if(((String)id).contains(",")){
            userMapper.deleteByIds(((String)id).split(","));
        }else {
            userMapper.deleteById(id);
        }
    }

    @Override
    public String modifyAvatar(Integer id, MultipartFile file) {
        // 上传文件
        String url = fileService.upload(file);

        // 更新头像
        User user = new User();
        user.setId(id);
        user.setAvatar(url);
        userMapper.update(user);

        return url;
    }
}
